<?php
include('../class/class_connect.php');
include('class/class_mobilepage.php');
include('../class/class_comments.php');
include('class/abstract/class_paginator.php');
include('../class/class_workdays.php');
include('../class/class_workdaysFilter.php');
include('../class/class_geo.php');
include('../class/class_rating.php');
include('../class/city_rus.php');
include('../class/class_checkGetData.php');
$aCheck=new checkGetData('f');
if($_GET['city'])$aCheck->checkCity($_GET['city']);


session_start();
class aFirmPage extends page
{
	var $row=array();
	var $cityRus;
	function __construct()
	{
		$aConnect=new connect('f');
		if($_GET['city'])$this->row=mysql_fetch_array($aConnect->select_all($_GET['city'], "WHERE subdiv='".$_GET['subdiv']."'"));
		$this->cityRus=new city_rus_class();
		parent::__construct();
	}
	function title()
	{
		echo $this->row['subdiv'].' '.$this->cityRus->city_rus_im($_GET['city']);
	}
	function maincontent()
	{		$geo=new geo();
		$workdaysFilter=new workdaysFilter();
		if(!$_GET['city'])
		{
			echo '<center><h1>Выберите город!</h1></center>';
		}
		else
		{
			$wdStyle='';
			$selected='';
			if($_POST['filter']=='byWorkdays')
			{
				$wdStyle='style="display: block;"';
				$selected='selected';
			}

			$wdRus=array(
					'mon'=>'пн',
					'tue'=>'вт',
					'wed'=>'ср',
					'thi'=>'чт',
					'fri'=>'пт',
					'sat'=>'сб',
					'sun'=>'вс'
				);
			echo ('
			<div class="route">
				<div class="routeEl">
					<a href="division.php?city='.$_GET['city'].'&division='.$this->row['division'].'">'.$this->row['division'].'</a>
				</div>
				<div class="routeEl">
					'.$_GET['subdiv'].'
				</div>
			</div>
			<script type="text/javascript" src="http://pro-gorod.com/scripts/subdivFilter.js">
			</script>
			<link rel="stylesheet" type="text/css" href="/style/subdivFilter.css" />
			<div class="filter">
				<center>
				<form name="filter" action="" method="post">
					упорядочить:
			');
			if(!$_GET['near'])
				echo ('
					<div id="showNear" class="button button-blue">
						по близости к Вашему местоположению
					</div>
				');
			else
			{
				echo ('
					<div id="showAll" class="button button-blue">
						по рейтингу
					</div>
				');
			}
			$pageAddress=$_SERVER['REQUEST_URI'];
			if($_GET['near'])
			{				$gets=explode('&', $_SERVER['REQUEST_URI']);
				foreach($gets as $key=>$vol)
				{					if($vol=='near=true')
						unset($gets[$key]);				}
				if($gets)$pageAddress=implode('&', $gets);			}
			echo ('
					<div id="info">
					<input name="pageAddress" id="pageAddress" type="hidden" value="'.$pageAddress.'">
					</div>
					<br />
					Режим работы:<br />
					<select size="1" name="filter" class="chooseFilter">
		  				<option id="byRating" value="byRating">Любой</option>
		  				<option id="byWorkdays" value="byWorkdays" '.$selected.'>Выбрать</option>
					</select>
				<div class="filterOptions">
					<div class="wdfilter" '.$wdStyle.'>
						<select size="1" name="weekday">
						');
						foreach($wdRus as $eng=>$rus)
						{
							$selected='';
							if($_POST['weekday']==$eng)
								$selected='selected';
							elseif($eng==strtolower(substr(date('l'), 0, 3)))
								$selected='selected';
							echo ('
			  				<option value="'.$eng.'" '.$selected.'>'.$rus.'</option>
			  				');
			  			}
			  			echo ('
						</select>
						минимум до:
						<select size="1" name="worktime">
			  			');
			  			$sel=false;
			  			if(!$_POST['workdays'])
			  			{
			  				$nearestHour=date('G')+1;
						}
						for($i=0; $i<24; $i++)
						{
							$selected='';
							$hour=$i;
							if($i<10)$hour='0'.$i;
							if($_POST['worktime']==$hour)
							{
								$selected='selected';
								$sel=true;
							}
							if(!$sel && $hour==$nearestHour)$selected='selected';
							echo ('
			  				<option value="'.$hour.'" '.$selected.'>'.$hour.'</option>
			  				');
			  			}
			  			echo ('
						</select>
						часов
						<input type="submit" id="filterBut" value="Показать" class="button button-blue">
					</div>
				</div>
				</form>
				</center>
			</div>
			');
			$aConnect=new connect('f');
			$like=$workdaysFilter->getLike();//если нужно отфильтровать по часам работы
			if($_GET['near'] && $_SESSION['longitude'] && $_SESSION['latitude'])//если нужно выдать по приближенности к юзеру
			{
				$mylatitude=$_SESSION['latitude'];
				$mylongitude=$_SESSION['longitude'];//координаты пользователя
				$res=$aConnect->select_all($_GET['city'], "WHERE subdiv='".$_GET['subdiv']."' ".$like." ORDER BY rating DESC");
				$minSpace=array();
				while($row=mysql_fetch_array($res))//ищем по всем фирмам раздела
				{					$space=array();
					$positions=explode(',', $row['positions']);
					foreach($positions as $key=>$pos)
					{
						$posEls=explode(' ', $pos);//координаты адресов фирмы
						$s=$geo->getSpaceBetweenPositions($mylatitude, $posEls[1], $mylongitude, $posEls[0]);
						$space[$pos]=round($s);//массив расстояний от каждого адреса фирмы до пользователя
					}
					$minSp=min($space);//выбираем ближайший к пользователю адрес фирмы
					$address=explode('|', $row['address']);
					if(!$like)//не фильтруем по часам работы
					{
						$keys=array_keys($space, $minSp);
						$minPosition=$keys[0];
						$minSpace[$row['id'].','.$minPosition]=$minSp;//массив ближайших адресов каждой фирмы
					}
					else //фильтруем по часам работы
					{
						foreach($address as $key=>$vol)
						{
							$keys=array_keys($space, $minSp);
							$minPosition=$keys[0];
							$wdCheck=true;							if($workdaysFilter->wdCheck($row['address'], $minPosition))//если проходит фильтр по часам работы
							{
								$minSpace[$row['id'].','.$minPosition]=$minSp;
								break;
							}
							else //если не проходит ближайший адрес проверяем следующий по приближенности и т.д.
							{								$key=array_keys($space, $minSp);
								if($key[0]===0 || $key)unset($space[$key[0]]);
								if(count($space)>0)$minSp=min($space);//если ни один адрес не проходит, знчит фирма не показывается							}
						}
					}
				}
				if($minSpace)//если после фильтра есть хоть одна фирма
				{
					asort($minSpace); //сортируем по приближенности
					$nearestFirms=array();
					foreach($minSpace as $id=>$value)
						$nearestFirms[]=$value.','.$id;//записываем расстояние и id фирм в массив в порядке приближенности
				}
			}
			else
			{				$res=$aConnect->select_all($_GET['city'], "WHERE subdiv='".$_GET['subdiv']."' ".$like." order BY rating DESC");
				while($row=mysql_fetch_array($res))
				{					$address=explode('|', $row['address']);					foreach($address as $key=>$addr)
					{						$addrEls=explode('^', $addr);
						$workdays=$addrEls[4];
						if($workdaysFilter->wdch($workdays))
						{
							$addressKey=$key;
							break;
						}					}
					$nearestFirms[]='noPosition,'.$row['id'].','.$addressKey;
				}			}
			$afirmsList=new firmsList($nearestFirms);// постраничный вывод отфильтрованных фирм
		}
	}
}
class firmsList extends paginator
{
	var $firmsNum;
	var $nearestFirms=array();
	function __construct($nearestFirms)
	{
		$this->nearestFirms=$nearestFirms;
		parent::__construct(7);
	}
	function countRows()
	{
		$this->firmsNum=count($this->nearestFirms);
		return $this->firmsNum;
	}
	function pageContent()
	{
		$workdays=new workdays();
		echo ('<link rel="stylesheet" type="text/css" href="style/mobsubdiv.css" />');
		if(!$this->firmsNum)echo '<center><h2>НИЧЕГО НЕ НАЙДЕНО<h2></center>';
		for($i=$this->lim; $i<$this->lim+$this->limit && $i<count($this->nearestFirms); $i++)
		{
			$aConnect=new connect('f');
			$firmsEls=explode(',', $this->nearestFirms[$i]);
			$id=$firmsEls[1];
			$space=$firmsEls[0];
			$position=$firmsEls[2];
			if($space>1000 && $space<10000)$space=(round($space/1000,1)).'км';
			elseif($space>10000)$space=(round($space/1000)).'км';
			elseif($space>0 && $space<1000)$space=substr($space, 0, strlen($space)-1).'0м';
			else $space.='м';
			$this->row=mysql_fetch_array($aConnect->select_all($_GET['city'], "WHERE id='".$id."'"));
			echo ('
			<div class="subdivFirm" align="center">
			');
			if($firmsEls[0]!='noPosition')
				echo ('
				<div class="space">'.$space.' от Вас</div>
				');
			echo ('
				<div class="nameShort" align="center">
					<div class="subdivFirmsName">
						<h4><a href="firms.php?city='.$_GET['city'].'&id='.$this->row['id'].'">'.$this->row['name'].'</a></h4>
					</div>
					<div class="subdivFirmsShort">
						'.$this->row['short'].'
					</div>
				</div>
				<table border="0" class="subdivTable">
					<tr>
						<td colspan="2" align="center">
							<a href="firms.php?city='.$_GET['city'].'&id='.$this->row['id'].'"><img class="subdivPic"
							src="http://pro-gorod.com/pictures/firmspics/'.$_GET['city'].'/'.$this->row['id'].'.jpg" title="'.$this->row['name'].'""></a>
						</td>
					</tr>
					<tr class="rateComs">
					<td>
				');

							$aFirmRating=new rating('f');
							$aFirmRating->echo_rating(0, $this->row['rating'], $this->row['votes']);
				echo ('
					</td>
					<td>
				');
							$aConnect=new connect('fc');
							$commentsNum=mysql_num_rows($aConnect->select_all($_GET['city'], "WHERE f_id='".$this->row['id']."'"));
				echo ('
							<a class="commentLink" href="comments.php?city='.$_GET['city'].'&id='.$this->row['id'].'&obj=firms"><font color="grey">отзывов:</font> '.$commentsNum.'</a>
						</td>
					</tr>
					<tr>
						<td align="center" colspan="2" class="finfo">
						');
						$addressArray=explode('|', $this->row['address']);
						$address=$addressArray[0];
						foreach($addressArray as $key=>$addr)
						{							$addrEls=explode('^', $addr);
							if($position==$addrEls[5])
								$address=$addressArray[$key];
							if($firmsEls[0]=='noPosition' && $_POST['worktime'])
							{
								$address=$addressArray[$position];
							}						}
						$thisAddressArray=explode('^', $address);
						$mallsArray=explode(',', $thisAddressArray[3]);
						echo ('
						<table border="0" align="left">
							<tr>
								<td class="namesCol">
									<img src="images/address.jpg" />
								</td>
								<td width="" class="addressTd">
									 '.$thisAddressArray[0].', '.$thisAddressArray[1].'
								</td>
							</tr>
							<tr  align="center">
								<td colspan="2" class="mallsCol">
									 '.$mallsArray[2].' '.$mallsArray[1].'
								</td>
							</tr>
							');
							if($thisAddressArray[2])
							echo ('
							<tr>
								<td class="namesCol">
									<img src="images/phone.jpg" />
								</td>
								<td class="phoneTd">
								 '.$thisAddressArray[2].'
								</td>
							</tr>
							');
							echo ('
							<tr>
								<td class="namesCol">
									<img src="images/clock.jpg" />
								</td>
								<td class="wdTd">
								');
									$workdays->showWorkdays($thisAddressArray[4]);
								echo ('
								</td>
							</tr>
						');
						if(count($addressArray)>1)
						{
							echo ('
							<tr>
								<td colspan="2" class="manyAddresses" align="center">
									Имеются другие адреса
								</td>
							</tr>
							');
						}
                       echo ('
                       		<tr>
                       			<td class="namesCol">
                       				<img src="images/site.jpg" />
                       			</td>
                       			<td class="webTd">
                       		');
                       		if($this->row['link'])
                       			echo '<a href="http://'.$this->row['link'].'">www.'.$this->row['link'].'</a>';
                       		else
                       			echo ('не указан');
                       		echo ('
                       			</td>
                       		</tr>
                       		</table>
                       	</td>
					</tr>
				</table>
			</div>
			');
        }
	}
}
$aPage=new aFirmPage();

?>